#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@FileName : bisection_auto.py
@Version : 1.0
@Date : 2023/6/19 14:11
"""

import math
from root_paras import Paras
from find_section import find_section


def bi_sect_auto(fun, paras: Paras = Paras()):
    a, b = find_section(fun, paras)
    if fun(a) * fun(b) > 0:
        raise ValueError("fun(a_)*fun(b) <= 0 not satisfied!")

    if b < a:
        b, a = a, b

    n: int = 0
    loops: int = paras.loops
    sol_tol = paras.sol_tol
    sec_tol = paras.sec_tol
    while (b - a) / 2.0 > sec_tol:
        n += 1
        if n > loops:
            raise RuntimeError(f'Bisection iteration: loop over 1000 times, with section {b - a}')

        c = float(a + b) / 2.0
        if math.fabs(fun(c) - 0) <= sol_tol:  # c是一个解，完成
            break
        if fun(a) * fun(c) < 0:
            b = c
        else:
            a = c

    print(n)
    return (a + b) / 2.0


if __name__ == '__main__':
    res = bi_sect_auto(lambda x: x ** 3 + x - 1)
    print(res)
